/**爬取豆瓣热门电影 */
const puppeteer = require('puppeteer');
const url = "https://movie.douban.com/";

function waitTime() {
    return new Promise(resolve => {
        setTimeout(resolve, 2000);
    });
}
(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(url, {
        waitUntil: 'networkidle2'
    });
    //await  waitTime();
    // await page.screenshot({path: 'example.png'});
    const fdata = await page.evaluate(() => {
        let farr = [];
        const $list = $('.gaia-movie .slide-container .slide-wrapper .slide-page');
        for (let index = 0; index < $list.length; index++) {
            let element = $list[index];
            let $item = $(element).children('.item');
            for (let index = 0; index < $item.length; index++) {
                const element = $item[index];
                let detailUrl = $(element).attr('href'); //电影详情地址
                let movieName = $(element).children('.cover-wp').children('img').attr('alt');
                let moviePic = $(element).children('.cover-wp').children('img').attr('src');
                farr.push({ detailUrl, movieName, moviePic });
            }
        }
        return farr;
    });
    // console.log(data)
    for (let index = 0; index < fdata.length; index++) {
        const item=    fdata[index];
        const detailUrl = item.detailUrl;
        await page.goto(detailUrl, {
            waitUntil: 'networkidle2'
        });
        delete item.detailUrl;
        const sdata = await page.evaluate(() => {
            let directs = [];//导演
            for (let index = 0; index < $('[rel="v:directedBy"]').length; index++) {
                directs.push($('[rel="v:directedBy"]')[index].text);
            }
            let starrs = []; //主演
            for (let index = 0; index < $('[rel="v:starring"]').length; index++) {
                if(index<3){
                    starrs.push($('[rel="v:starring"]')[index].text);
                }
              
            }
            let genre=$('[property="v:genre"]').html(); //类型
            let initialReleaseDate=$('[property="v:initialReleaseDate"]').html(); //上映时间
            let average=$('[property="v:average"]').html(); //评分
            let summary=$('[property="v:summary"]').html(); //简介
            return {directs,starrs,genre,initialReleaseDate,average,summary};
        });
        Object.assign(item, sdata);
        console.log(item)
    }


    await browser.close();


})();